package com.veselinov.dictspeach.search.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class HttpCall {
	// An asynchronous task is defined by 3 generic types, called Params,
	// Progress and Result,
	// and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and
	// onPostExecute.

	public HttpCall() {
		// TODO Auto-generated constructor stub
	}

	// ---Connects using HTTP GET---
	public InputStream OpenHttpGETConnection(String url) {
		InputStream inputStream = null;
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
			inputStream = httpResponse.getEntity().getContent();
		} catch (Exception e) {
			Log.d("InputStream", e.getLocalizedMessage());
		}
		return inputStream;
	}

	public String DownloadText(String URL) {
		int BUFFER_SIZE = 2000;
		InputStream in = null;
		try {
			in = OpenHttpGETConnection(URL);
		} catch (Exception e) {
			Log.d("DownloadText", e.getLocalizedMessage());
			return "";
		}
		InputStreamReader isr = new InputStreamReader(in);
		int charRead;
		String str = "";
		char[] inputBuffer = new char[BUFFER_SIZE];
		try {
			while ((charRead = isr.read(inputBuffer)) > 0) {
				// ---convert the chars to a String---
				String readString = String
						.copyValueOf(inputBuffer, 0, charRead);
				str += readString;
				inputBuffer = new char[BUFFER_SIZE];
			}
			in.close();
		} catch (IOException e) {
			Log.d("DownloadText", e.getLocalizedMessage());
			return "";
		}
		return str;
	}

}
